package com.ly.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname TestCyclicBarrier
 * @Description TODO
 * @Date 2020/10/4 16:50
 * @Author 冷心影翼
 */
public class TestCyclicBarrier {

	public static void main(String[] args) throws InterruptedException {
		cyclicBarrier();
	}

	public static void cyclicBarrier() throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(10);
		Barrier barrier = new Barrier();
		for(int i=0;i<10;i++) {
			new Thread(()->{
				barrier.protect();
				countDownLatch.countDown();
			}).start();
		}
		countDownLatch.await();
		if (barrier.isEnd()) {
			barrier.nextTurn();
			for(int i=0;i<10;i++) {
				new Thread(()->{
					barrier.protect();
				}).start();
			}
		}
	}
}


class Barrier {

	int monsterNumber = 10;

	int n = 1;

	CyclicBarrier cyclicBarrier;

	Lock lock = new ReentrantLock();

	public Barrier(){
		cyclicBarrier = new CyclicBarrier(monsterNumber,()->{
			System.out.println("第"+n+"波进攻结束");
		});
	}

	public void killMonster() {
		lock.lock();
		try {
			monsterNumber--;
			System.out.println("剩余怪物数量:"+monsterNumber);
		}catch (Exception e){

		}finally {
			lock.unlock();
		}
	}

	public void protect() {
		killMonster();
		try {
			cyclicBarrier.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			e.printStackTrace();
		}
		System.out.println("修整栅栏和障碍物ing");
	}

	public void nextTurn() {
		n++;
		monsterNumber = 10;
		cyclicBarrier.reset();
	}

	public boolean isEnd() {
		return cyclicBarrier.getNumberWaiting() == 0;
	}
}